/*
Simple Forum Auto Poster.
Copyright (C) 2011 Gianni Van Hoecke.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package domain.net;

import domain.DomainController;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.swing.text.html.HTML.Attribute;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import persistence.net.Client;

/**
 *
 * @author Gianni Van Hoecke <gianni.vh@gmail.com>
 * Tries to search for recaptcha images.
 */
public class CaptchaUtils
{
    /**
     * Evaluates the recaptcha method. It will ask the user for the captca code.
     * @param client The working client.
     * @param content The content of the page which contains the captcha iframe.
     * @return A list containing the captcha secret code that you must add to the NameValuePairs when posting.
     * @throws Exception On error.
     */
    public static List<NameValuePair> evaluateRecaptcha(Client client, String content) throws Exception
    {
        List<NameValuePair> nvp = new ArrayList<NameValuePair>();

        /*
         <iframe src="http://api.recaptcha.net/noscript?k=6Lc_Wb0SAAAAAPpDWSnsxg7rFxSJT46Wmic3Ximb" height="300" width="500" frameborder="0"></iframe>
         */

        List<String> iframe_src = HTMLParser.getSRC(new StringReader(content));

        for(String src : iframe_src)
        {
            if(src.startsWith("http://api.recaptcha.net/noscript"))
            {
                //Match! Extract image!
                client.doGet(src);
                String iframe = client.getResponseContent();
                List<String> img_src = HTMLParser.getSRC(new StringReader(iframe));
                for(String s : img_src)
                {
                    if(s.startsWith("image?"))
                    {
                        String code = "http://api.recaptcha.net/" + s;
                        String captcha = DomainController.getInstance().askCaptchaCode(code);
                        
                        DomainController.getInstance().getLogger().log(Level.INFO, "You have entered: {0}", captcha);

                        //recaptcha_challenge_field=03AHJ_Vut [...]
                        //recaptcha_response_field=Zhang%2C+portnoe
                        //submit=I%27m+a+human
                        List<String> inputs = HTMLParser.extractValueFromTag(new StringReader(iframe), javax.swing.text.html.HTML.Tag.INPUT, Attribute.ID, "recaptcha_challenge_field", Attribute.VALUE);

                        if(inputs.size() > 0)
                        {
                            DomainController.getInstance().getLogger().log(Level.INFO, "Captcha correct!");

                            List<NameValuePair> iframeNVP = new ArrayList<NameValuePair>();
                            iframeNVP.add(new BasicNameValuePair("recaptcha_challenge_field", inputs.get(0)));
                            iframeNVP.add(new BasicNameValuePair("recaptcha_response_field", captcha));
                            iframeNVP.add(new BasicNameValuePair("submit", "I'm a human"));

                            client.doPost(src, iframeNVP);
                            String iframeResponse = client.getResponseContent();

                            List<NameValuePair> tempNVP = HTMLParser.getTextAreaContent(new StringReader(iframeResponse));

                            String theCodeWeNeed = tempNVP.get(0).getValue();

                            nvp.add(new BasicNameValuePair("recaptcha_challenge_field", theCodeWeNeed));
                            nvp.add(new BasicNameValuePair("recaptcha_response_field", "manual_challenge"));
                            nvp.add(new BasicNameValuePair("captcha-type", "recaptcha"));
                        }
                        else
                        {
                            DomainController.getInstance().getLogger().log(Level.INFO, "Captcha incorrect!");
                        }
                        break;
                    }
                }
                break;
            }
        }
        return nvp;
    }
}